package com.mine;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.common.pojo.app.UserInfoPojo;
import com.common.pojo.dto.Result;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.common.utils.MD5Utils;
import com.mine.databinding.ActivityChangePasswordBinding;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class ChangePasswordActivity extends AppCompatActivity {


    private EditText newPasswordEditText;
    private EditText confirmPasswordEditText;
    private Button changePasswordButton;
    private ImageView backButton;
    private ActivityChangePasswordBinding changePasswordBinding;
    private UserInfoPojo userInfo;
    private boolean passwordVisible = false;
    private boolean confirmPasswordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changePasswordBinding = ActivityChangePasswordBinding.inflate(getLayoutInflater());
        setContentView(changePasswordBinding.getRoot());
        initViews();
        setupListeners();
        userInfo = JSONObject.parseObject(Constants.userInfo, UserInfoPojo.class);
    }

    private void initViews() {
        newPasswordEditText = changePasswordBinding.newPasswordEditText;
        confirmPasswordEditText = changePasswordBinding.confirmPasswordEditText;
        changePasswordButton = changePasswordBinding.changePasswordButton;
        backButton = changePasswordBinding.backButton;
    }

    private void setupListeners() {
        changePasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                validateAndChangePassword();
            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        //点击密码眼睛
        changePasswordBinding.togglePasswordVisibility.setOnClickListener(v -> {
            passwordVisible = !passwordVisible;
            if (passwordVisible) {
                // 显示密码
                changePasswordBinding.newPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                changePasswordBinding.togglePasswordVisibility.setImageResource(R.drawable.ic_eye);
            } else {
                // 隐藏密码
                changePasswordBinding.newPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                changePasswordBinding.togglePasswordVisibility.setImageResource(R.drawable.ic_eye_closed);
            }

            // 光标定位到文本末尾
            changePasswordBinding.newPasswordEditText.setSelection(changePasswordBinding.newPasswordEditText.getText().length());

        });
        //点击再次确认密码眼睛
        changePasswordBinding.toggleConfirmPasswordVisibility.setOnClickListener(v -> {
            confirmPasswordVisible = !confirmPasswordVisible;
            if (confirmPasswordVisible) {
                // 显示密码
                changePasswordBinding.confirmPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                changePasswordBinding.toggleConfirmPasswordVisibility.setImageResource(R.drawable.ic_eye);
            } else {
                // 隐藏密码
                changePasswordBinding.confirmPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                changePasswordBinding.toggleConfirmPasswordVisibility.setImageResource(R.drawable.ic_eye_closed);
            }

            // 光标定位到文本末尾
            changePasswordBinding.confirmPasswordEditText.setSelection(changePasswordBinding.confirmPasswordEditText.getText().length());

        });
    }

    private void validateAndChangePassword() {
        String newPassword = newPasswordEditText.getText().toString().trim();
        String confirmPassword = confirmPasswordEditText.getText().toString().trim();

        // 验证新密码
        if (TextUtils.isEmpty(newPassword)) {
            newPasswordEditText.setError("请输入新密码");
            newPasswordEditText.requestFocus();
            return;
        }

        if (newPassword.length() < 6) {
            newPasswordEditText.setError("密码长度至少为6位");
            newPasswordEditText.requestFocus();
            return;
        }

        // 验证确认密码
        if (TextUtils.isEmpty(confirmPassword)) {
            confirmPasswordEditText.setError("请确认新密码");
            confirmPasswordEditText.requestFocus();
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            confirmPasswordEditText.setError("两次输入的密码不一致");
            confirmPasswordEditText.requestFocus();
            return;
        }

        // 模拟修改密码成功
        simulatePasswordChange();
    }

    private void simulatePasswordChange() {
        // 这里应该调用API进行密码修改
        // 模拟网络请求延迟
        changePasswordButton.setEnabled(false);
        changePasswordButton.setText("修改中...");
        String string = newPasswordEditText.getText().toString();
        OkHttpUtils.get().url(ConstantsUrl.modifyPassUrl)
                .addParams("email", userInfo.getEmail())
                .addParams("password", MD5Utils.encrypt(string))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
                changePasswordButton.setText("修改密码");
            }

            @Override
            public void onResponse(String response, int id) {
                changePasswordButton.setText("修改密码");
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("注册请求返回失败");
                }
                showToast(result.getMessage());
            }
        });
    }

    private void showToast(String content) {
        Toast.makeText(ChangePasswordActivity.this, content, Toast.LENGTH_SHORT).show();
    }
}